package org.yi.fc.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * cookie的增加、删除、查询
 */
public class CookieUtils {
	
    private static Logger logger = LoggerFactory.getLogger(CookieUtils.class);
    
    public static final String USER_COOKIE = "user.cookie";
    public static final String READ_HISTORY_COOKIE = "read.history.cookie";

    /*// 添加一个cookie
    public static <T> Cookie addUserCookie(T user) {
        try {
            Cookie cookie = new Cookie(USER_COOKIE, URLEncoder.encode(user.getLoginid(), YiDuConstants.ENCODING_UTF_8)
                    + "," + user.getPassword());
            cookie.setMaxAge(60 * 60 * 24 * 14);// cookie保存两周
            return cookie;
        } catch (UnsupportedEncodingException e) {
            logger.error(e);
        }
        return null;
    }

    *//**
     * 使用cookie信息登录
     * 
     * @param request
     * @param userService
     *//*
    public static void getUserCookieAndLogoin(HttpServletRequest request, UserService userService) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            // 遍历cookie查找用户信息
            for (Cookie cookie : cookies) {
                if (CookieUtils.USER_COOKIE.equals(cookie.getName())) {
                    // 使用cookie内的用户信息登录
                    String value = cookie.getValue();
                    if (StringUtils.isNotBlank(value)) {
                        String[] split = value.split(",");
                        if (split.length == 2) {
                            String loginid = split[0];
                            String password = split[1];
                            TUser user = userService.findByLoginInfoByJDBC(loginid, password);
                            if (user != null) {
                                LoginManager.doLogin(user);
                                // 更新用户最后登录时间
                                userService.updateLastLoginDate(user.getUserno(),new Date());
                            }
                        }
                    }
                }
            }
        }
    }*/

    // 删除cookie
    public static Cookie delUserCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (USER_COOKIE.equals(cookie.getName())) {
                	logger.trace("delete cookie: " + USER_COOKIE);
                    cookie.setValue("");
                    cookie.setMaxAge(0);
                    return cookie;
                }
            }
        }
        return null;
    }

}
